<template>
  <div
    v-show="isShow"
    id="sc-content-drop-area"
    class="sc-content-drop-area"
    :class="{
      dragover
    }"
    :style="styleVm"
    @dragover="dragover = true"
    @dragleave="dragover = false"
    @dragover.prevent
  >
    <div class="left-panel" @drop="handleDropLeft">
      <div class="sc-content-drop-area-content">
        <div class="icon"><div class="fake-svg"></div></div>
        <div class="title">拖放图片到这里</div>
        <div class="description">
          将图片拖放到这里，迅速添加到 Share Creators 里。
        </div>
      </div>
    </div>
    <div class="right-panel sc-text-info sc-pt-36">
      <div v-if="isLogin">
        <div v-if="userFolders.length === 0">无个人文件夹</div>
        <div v-else>
          <div
            class="list-item-folder"
            v-for="userFolder in userFoldersVm"
            :key="userFolder.ASSET_LABEL_SEQ"
            :class="{ dragover: userFolder.isDragOver }"
            @dragenter="$set(userFolder, 'isDragOver', true)"
            @dragleave="$set(userFolder, 'isDragOver', false)"
            @drop="handleDropUserFolder(userFolder)"
          >
            {{ userFolder.LABEL_NAME }}
          </div>
          <div
            class="list-item-folder"
            :class="{ dragover: selectFolderButton.isDragOver }"
            @dragenter="selectFolderButton.isDragOver = true"
            @dragleave="selectFolderButton.isDragOver = false"
            @drop="handleDropSelectFolder(userFolder)"
          >
            选择文件夹
          </div>
        </div>
      </div>
      <div v-else class="sc-content-drop-folder-selection">
        <div style="color: #d1d1d1; font-size: 14px">未登录</div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { eachTree, throttle } from "xe-utils";

import { labelTypePrivate, labelTypeTeam } from "@/constant";
import { getFolderTree } from "@/api/folder";
import { saveToBlueberryApi } from "@/contentUtils/utils";
import { toDataUrlAsync } from "@/contentUtils/toDataUrlFromUrl";
import {
  getDragConfig,
  getElementBackgroundImage,
  getHasSrcTarget
} from "@/contentUtils/contenters/drag-config";
import { checkIsLoginAsync } from "@/logics/chrome/user";

const dragMode = 1;
const DIALOG_KEY = "DragUploadLayer";
export default {
  name: DIALOG_KEY,
  // components: { SelectTree, Splitpanes, Pane },
  data() {
    return {
      isOperated: false,
      selectedFolderTeam: null,
      selectedFolderPrivate: null,
      activeTreeTab: labelTypePrivate,
      labelTypeTeam,
      labelTypePrivate,
      left: 100,
      top: 100,
      isShow: false,
      isLogin: false,
      dragover: false,

      pageX: 0,
      pageY: 0,
      clientX: 0,
      clientY: 0,

      target: null,
      userFolders: [],
      selectFolderButton: {
        isDragOver: false
      }
    };
  },
  computed: {
    ...mapState("orange", {
      dialogInfo: state => state.dialog[DIALOG_KEY]
    }),
    styleVm() {
      return {
        left: Math.max(0, this.left) + "px",
        top: Math.max(0, this.top) + "px"
      };
    },
    resFormData() {
      return this.formData;
    },
    selectedFolderVm() {
      if (this.activeTreeTab === this.labelTypeTeam) {
        return this.selectedFolderTeam;
      }
      return this.selectedFolderPrivate;
    },
    // 按时间顺序展示前5个
    userFoldersVm() {
      // 使用插入排序，从 this.userFolders 中取出ASSET_LABEL_SEQ 最大的前5个
      const flatFolders = [];
      eachTree(this.userFolders, treeFolder => {
        for (let i = 0; i < flatFolders.length; i++) {
          const flatFolder = flatFolders[i];
          if (treeFolder.ASSET_LABEL_SEQ > flatFolder.ASSET_LABEL_SEQ) {
            flatFolders.splice(i, 0, treeFolder);
            if (flatFolders.length > 5) {
              flatFolders.pop();
            }
            return;
          }
        }
        if (flatFolders.length < 5) {
          flatFolders.push(treeFolder);
          return;
        }
      });

      return flatFolders;
    }
  },
  methods: {
    /** 锁定异步事件，防止重复触发 */
    async lockAction(func) {
      this.isOperated = true;
      try {
        await func();
      } finally {
        this.isOperated = false;
      }
    },
    /** 1、开始拖拽，判断是否可以拖拽到系统中 */
    async handleDragStart(event) {
      if (!event.target || !event.target.nodeName) {
        return;
      }
      // 1、判断拖拽元素是否 a img vedio
      if (
        !["img", "a", "video"].includes(event.target.nodeName.toLowerCase())
      ) {
        return;
      }
      // 2、判断是否开启拖拽
      const { isPage, isDomain } = getDragConfig();
      if (!isPage || !isDomain) {
        return;
      }

      // 3、判断元素属于可编辑元素的子元素
      if (event.target.closest("[contenteditable='true']")) {
        //可编辑元素中的图片不能拖拽
        return;
      }

      var { target, targetLink } = getHasSrcTarget(event);
      if (!target) {
        console.log("无法拖拽 target为空");
        return;
      }
      var src = getElementBackgroundImage(target);
      if (!src) {
        console.log("无法拖拽 src为空");
        return;
      }
      this.target = target;

      //5、检查是否登录
      this.checkIsLogin();

      //6、弹出可拖拽区域
      const dragstartX = event.clientX;
      const dragstartY = event.clientY;
      setTimeout(() => {
        var offsetX = Math.abs(dragstartX - this.clientX);
        var offsetY = Math.abs(dragstartY - this.clientY);
        if (offsetX > 1 || offsetY > 1) {
          // 左右
          if (offsetX > offsetY && dragMode === 1) {
            if (dragstartX <= this.clientX) {
              this.showDropArea({
                orientation: "Right",
                dragstartX,
                dragstartY
              });
            } else {
              this.showDropArea({
                orientation: "Left",
                dragstartX,
                dragstartY
              });
            }
          } else {
            if (dragstartY >= this.clientY) {
              this.showDropArea({ orientation: "Top", dragstartX, dragstartY });
            } else if (dragstartY < this.clientY) {
              this.showDropArea({
                orientation: "Bottom",
                dragstartX,
                dragstartY
              });
            }
          }
        }
      }, 100);
    },
    showDropArea({ dragstartX, dragstartY, orientation }) {
      var left = dragstartX;
      var top = dragstartY;
      if (dragstartX === 0 && dragstartY === 0) return;
      if (orientation === "Top") {
        left = left - 120;
        top = top - 240 - 80;
        if (top < 0) top = 0;
        if (left + 240 > window.innerWidth) left = window.innerWidth - 240;
      } else if (orientation === "Bottom") {
        left = left - 120;
        top = top + 80;
        if (top < 0) top = 0;
        if (left + 240 > window.innerWidth) left = window.innerWidth - 240;
      } else if (orientation === "Right") {
        left = left + 80;
        top = top - 120;
        if (top < 0) top = 0;
        if (left + 240 > window.innerWidth) left = window.innerWidth - 240;
      } else {
        top = top - 120;
        left = left - 80 - 240;
        if (top < 0) top = 0;
        if (left < 0) left = 0;
      }

      this.left = left;
      this.top = top;
      this.isShow = true;
    },
    handleMouseMove(event) {
      this.pageX = event.pageX;
      this.pageY = event.pageY;
      this.clientX = event.clientX;
      this.clientY = event.clientY;
    },
    async checkIsLogin() {
      this.isLogin = await checkIsLoginAsync();
      if (this.isLogin) {
        this.initDataThrottle();
      }
    },
    initDataThrottle: throttle(
      async function () {
        const foldersRes = await getFolderTree(labelTypePrivate);
        console.log("foldersRes", foldersRes);
        if (!foldersRes._success) {
          return;
        }
        this.userFolders = foldersRes.data || [];
        console.log("this.userFolders", this.userFolders);
      },
      60 * 1000,
      {
        leading: true
      }
    ),
    handleDragEnd(event) {
      console.log("3、handleDragEnd");
      this.isShow = false;
      this.target = null;
    },
    async handleDropLeft(e) {
      console.log("2、handleDropLeft");
      //如果未登录，提示登录
      if (!this.isLogin) {
        this.$openDialog("LoginPluginDlg");
        return;
      }
      const src = getElementBackgroundImage(this.target);
      if (!src) {
        console.error("无法识别的拖拽元素");
        this.isShow = false;
        this.target = null;
        return;
      }
      let base64;
      try {
        base64 = await toDataUrlAsync(src);
      } catch (e) {
        console.error("无法获取图片base64", e);
      }
      //直接上传到服务器
      saveToBlueberryApi({
        url: src,
        base64,
        folder: this.selectedFolderVm
      });
      this.isShow = false;
    },
    async handleDropUserFolder(userFolder) {
      this.$set(userFolder, "isDragOver", false);
      //如果未登录，提示登录
      if (!this.isLogin) {
        this.$openDialog("LoginPluginDlg");
        return;
      }
      const src = getElementBackgroundImage(this.target);
      if (!src) {
        console.error("无法识别的拖拽元素");
        this.isShow = false;
        this.target = null;
        return;
      }
      let base64;
      try {
        base64 = await toDataUrlAsync(src);
      } catch (e) {
        console.error("无法获取图片base64", e);
      }
      //直接上传到服务器
      saveToBlueberryApi({
        url: src,
        base64,
        folder: userFolder
      });
      this.isShow = false;
    },
    async handleDropSelectFolder() {
      this.selectFolderButton.isDragOver = false;
      //如果未登录，提示登录
      const src = getElementBackgroundImage(this.target);
      if (!src) {
        console.error("无法识别的拖拽元素");
        this.isShow = false;
        this.target = null;
        return;
      }
      let base64;
      try {
        base64 = await toDataUrlAsync(src);
      } catch (e) {
        console.error("无法获取图片base64", e);
      }
      //直接上传到服务器
      // saveToBlueberryApi({
      //   base64,
      //   folder: userFolder
      // });

      this.$openDialog("SaveFolderDlg", {
        imgBase64: base64,
        imgUrl: src
      });
      this.isShow = false;
    }
  },
  created() {
    console.log(this.isShow);
    document.body.addEventListener("dragstart", this.handleDragStart);
    document.body.addEventListener("mousemove", this.handleMouseMove);
    document.body.addEventListener("dragend", this.handleDragEnd);
  },
  beforeDestroy() {
    document.body.removeEventListener("dragstart", this.handleDragStart);
    document.body.addEventListener("mousemove", this.handleMouseMove);
    document.body.removeEventListener("dragend", this.handleDragEnd);
  }
};
</script>

<style lang="scss" scoped>
.sc-content-drop-area {
  font-family: "PingFang SC", "Hiragino Sans GB", "WenQuanYi Micro Hei",
    "Microsoft Yahei", "微软雅黑", "Helvetica Neue", Helvetica, Arial, Arial,
    sans-serif;
  font-weight: 400;
  z-index: 2147483647;
  position: fixed;
  height: 240px;
  width: 480px;
  text-align: center;
  transition: background 0.1s ease-in-out, opacity 0.1s ease-in-out,
    transform 0.2s ease-in-out, border 0.1s ease-in-out,
    box-shadow 0.1s ease-in-out;
  bottom: 0;
  /*-webkit-perspective: 1000;*/
  transform: translateY(10px);
  /*border: 1px solid rgba(255, 255, 255, 0.07);*/
  /*box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.4) 0 8px 24px rgba(65, 69, 100, .15);*/
  box-sizing: border-box;
  opacity: 0.95;
  background: #303034;
  box-shadow: 0 10px 20px 0 rgba(0, 0, 0, 0.2);
  border-radius: 8px;

  display: flex;
  padding: 10px 0;
  .left-panel {
    flex: 1;
    position: relative;
  }

  .right-panel {
    flex: 1;
    border-left: 1px solid #585858;
    /*border: 1px solid pink;*/

    .list-item-folder {
      color: #d1d1d1;
      text-align: left;
      font-size: 14px;
      padding: 3px 10px;
      transition: background-color 0.1s, border-radius 0.1s;
      margin: 0 4px;
      cursor: pointer;
      height: 25px;
      line-height: 19px;
      box-sizing: border-box;

      width: 230px;
      text-overflow: ellipsis;
      overflow: hidden;
      &.dragover {
        background: #17baa1;
        color: white;
        border-radius: 3px;
      }
    }
  }
}

.right-panel .sc-content-drop-folder-selection ul.sc-content-folders-list {
  list-style: none;
  padding-left: 0;
}

.right-panel .sc-content-drop-folder-selection .more {
  font-weight: 600;
  margin-top: 10px;
}

.sc-content-drop-area.sc-show {
  transition: transform 0.1s ease-out;
  transform: translateY(0px);
}

.sc-content-drop-area .sc-content-drop-area-content {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%) translateY(-50%);
  width: 180px;
  margin-top: 5px;

  /*border: 1px solid red;*/
}

.sc-content-drop-area .sc-content-drop-area-content .icon {
  height: 44px;
  width: 44px;
  line-height: 44px;
  text-align: center;
  margin: 0 auto 20px !important;
  /*background-color: rgba(51,51,51,0.05);*/
  background: rgba(255, 255, 255, 0.2);
  border-radius: 50%;
  transition: all 0.3s ease-in-out;
}

.sc-content-drop-area .sc-content-drop-area-content .icon .fake-svg {
  -webkit-mask: url()
    no-repeat center center;
  /*background: #333;*/
  height: 44px;
  width: 44px;
  background: #fff;
  transition: all 0.3s ease-in-out;
  animation: icon-jump 1.5s ease 0s infinite normal;
}

.sc-content-drop-area .sc-content-drop-area-content .icon img {
  display: inline-block;
  vertical-align: middle;
}

.sc-content-drop-area .sc-content-drop-area-content .title {
  font-family: "PingFang SC", "Hiragino Sans GB", "WenQuanYi Micro Hei",
    "Microsoft Yahei", "微软雅黑", "Helvetica Neue", Helvetica, Arial, Arial,
    sans-serif;
  font-size: 16px !important;
  font-weight: 400 !important;
  -webkit-font-smoothing: antialiased !important;
  -moz-osx-font-smoothing: grayscale !important;
  margin-bottom: 10px !important;
  color: #fff !important;
  transition: all 0.3s ease-in-out;
}

.sc-content-drop-area .sc-content-drop-area-content .description {
  font-family: "PingFang SC", "Hiragino Sans GB", "WenQuanYi Micro Hei",
    "Microsoft Yahei", "微软雅黑", "Helvetica Neue", Helvetica, Arial, Arial,
    sans-serif;
  font-size: 12px !important;
  font-weight: 400 !important;
  -webkit-font-smoothing: antialiased !important;
  -moz-osx-font-smoothing: grayscale !important;
  margin-bottom: 0 !important;
  line-height: 1.5 !important;
  color: #fff !important;
  opacity: 0.7;
  transition: all 0.3s ease-in-out;
}

.sc-content-drop-area.dragover .sc-content-drop-area-content .icon {
  background: rgba(255, 255, 255, 0.3);
  /*opacity: 0.9;*/
  /*transform: translateY(0) scale3d(1.05, 1.05, 1);*/
}
</style>
